package com.ctgu.chatapp.view

import android.content.Context
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.ctgu.chatapp.R
import com.ctgu.chatapp.databinding.ActivityStartBinding
import com.ctgu.chatapp.viewModel.StartViewModel

class Start : BaseActivity() {

    val binding by lazy {
        DataBindingUtil.setContentView(
            this,
            R.layout.activity_start
        ) as ActivityStartBinding
    }

    val viewModel: StartViewModel by lazy {
        ViewModelProvider(
            this,
            ViewModelProvider.AndroidViewModelFactory.getInstance(application)
        )[StartViewModel::class.java]
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        setContentView(binding.root)
    }

    override fun dispatchTouchEvent(ev: MotionEvent?) = run {
        if (ev != null) {
            if (ev.action == MotionEvent.ACTION_DOWN) {
                val v = currentFocus
                if (v?.let { isShouldHideInput(it, ev) } == true) {
                    val imm: InputMethodManager =
                        getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                    imm.hideSoftInputFromWindow(v.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
                    val item = window.decorView.findFocus()
                    item.clearFocus()
                }

            }
        }
        super.dispatchTouchEvent(ev)
    }

    private fun isShouldHideInput(view: View, ev: MotionEvent) = run {
        if (view is EditText) {
            val l = intArrayOf(0, 0)
            view.getLocationInWindow(l)
            val left = l[0]
            val top = l[1]
            val bottom = l[0] + view.height
            val right = l[1] + view.width
            ev.x <= left || ev.x >= right || ev.y <= top || ev.y >= bottom
        } else {
            false
        }
    }
    
}